﻿using Localization.Resources.AbpUi;
using NP.BPMReportPlatform.Localization;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Microsoft.Extensions.DependencyInjection;
using System;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace NP.BPMReportPlatform
{
    [DependsOn(
        typeof(BPMReportPlatformApplicationContractsModule),
        typeof(AbpAspNetCoreMvcModule))]
    public class BPMReportPlatformHttpApiModule : AbpModule
    {
        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            PreConfigure<IMvcBuilder>(mvcBuilder =>
            {
                mvcBuilder.AddApplicationPartIfNotExists(typeof(BPMReportPlatformHttpApiModule).Assembly);
            });
        }

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            Configure<AbpLocalizationOptions>(options =>
            {
                options.Resources
                    .Get<BPMReportPlatformResource>()
                    .AddBaseTypes(typeof(AbpUiResource));
            });
        }
    }

    /// <summary>
    /// 忽略返回结构化(顺序一定要在ApiResultFilterAttribute后面)
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class IgnoreApiResultAttribute : ResultFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is ObjectResult)
            {
                var objectResult = context.Result as ObjectResult;
                if (objectResult.Value == null)
                {
                    context.Result = new ObjectResult(string.Empty);
                }
                else
                {
                    if (objectResult.DeclaredType is null)
                    {
                        // 这边默认已经被封装过了，直接拆包
                        objectResult.Value =JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(objectResult.Value))["Result"].ToString();
                    }
                }
            }
        }
    }
}
